#ifndef MODBUSSERVER_H
#define MODBUSSERVER_H

#include <QThread>
#include <QString>
#include <QVector>
#include <QMutex>
#include <modbus.h>

class ModbusServer : public QThread
{
    Q_OBJECT

public:
    ModbusServer(int startAddress = 0);
    ~ModbusServer();

    void startTcpServer(const QString& address, int port =502, int slaveId = 1);
    void startSerialServer(const QString& device, int baudRate, int slaveId = 1);

    void setHoldingRegister(uint16_t address, uint16_t value);
    void setFloatHoldingRegister(uint16_t address, float value);
    uint16_t getHoldingRegister(uint16_t address);
    float getFloatHoldingRegister(uint16_t address);

    void setCoil(uint16_t address, bool value);
    bool getCoil(uint16_t address);

    void parseModbusRequest(const uint8_t *query, int received);
protected:
    void run() override;

private:
    void initModbusServer();
    void cleanupModbusServer();
    void handleRequest();
    void processTcpRequest();
    void processSerialRequest();
    void startServer();
    
    modbus_t *modbusContext;
    modbus_mapping_t *mbMapping;
    int serverType; // 0: TCP, 1: Serial
    QString serverAddress;
    int serverPort;
    QString serialDevice;
    int baudRate;
    int slaveId;
    int startAddress; // 起始地址
    int run_flag;
    QMutex mutex;
};

#endif // MODBUSSERVER_H
